const express = require('express')
const mysql = require('mysql')
const crypto = require('crypto')
const cors = require('cors')

const app = express()
app.use(express.json())
app.use(cors())

const connection = mysql.createConnection({
  host: '192.168.192.101',
  user: 'demo_server',
  password: 'RGsEFJksCEwddMPK',
  database: 'demo_server'
})

connection.connect()
// 登陆请求
app.post('/park/login', (req, res) => {
  const { username, password } = req.body
  if (!username || !password) {
    return res.status(400).send({ msg: '账号或密码错误' })
  }

  const query = 'SELECT * FROM hmzs_demo WHERE username = ? AND password = ?'
  connection.query(query, [username, password], (error, results) => {
    if (error) {
      return res.status(500).send({ msg: '服务器错误' })
    }
    if (results.length === 0) {
      return res.status(401).send({ msg: '账号或密码错误' })
    }
    const user = results[0]
    let token = user.token

    if (!token) {
      token = crypto.randomBytes(16).toString('hex')
      const updateQuery = 'UPDATE hmzs_demo SET token = ? WHERE id = ?'
      connection.query(updateQuery, [token, user.id], (error, results) => {
        if (error) {
          return res.status(500).send({ msg: '服务器错误' })
        }
      })
    }
    res.status(200).send({ msg: '登录成功', data: { token }})
  })
})

// 请求月卡列表
// 验证Token函数（这里仅作示例，实际应用中应使用更安全的方法）
function verifyToken(req, res) {
  let token = ''
  if (req.headers.authorization) {
    token = req.headers.authorization.split(' ')[1] // 假设Token以Bearer 开头
  }
  //   const token = req.headers.authorization.split(' ')[1]; // 假设Token以Bearer 开头
  if (!token) return res.status(401).send({ code: 401, msg: '请求携带的Token为空，请重新登录获取' })

  // 这里简化处理，实际应用中应查询数据库验证Token有效性
  connection.query('SELECT * FROM hmzs_demo WHERE token = ?', [token], (err, results) => {
    if (err) throw err
    if (results.length === 0) {
      return res.status(401).send({ code: 401, msg: '请求Token已过期' })
    }
  })
}

// 计算月卡剩余有效时间
function cardDate(startDate, endData) {
  const d1 = new Date(startDate)
  const d2 = new Date(endData)
  const timeDifference = Math.abs(d2 - d1)
  const days = Math.ceil(timeDifference / (1000 * 60 * 60 * 24))
  return days
}
app.get('/parking/card/list', (req, res) => {
  verifyToken(req, res)
  const page = parseInt(req.query.page) || 1
  const pageSize = parseInt(req.query.pageSize) || 10
  const carNumber = req.query.carNumber || ''
  const personName = req.query.personName || ''
  const cardStatus = req.query.cardStatus || ''

  console.log(typeof cardStatus)
  // 查找全部参数
  // 如果有查询参数进来就不使用分页功能
  console.log(carNumber || personName || cardStatus === '0' || cardStatus)
  if (carNumber || personName || cardStatus === '0' || cardStatus) {
    let query = `SELECT * FROM monthly_card`
    query += ' WHERE '
    //    判断三个都有值的情况
    if (carNumber && personName && (cardStatus === '0' || cardStatus)) {
      query += `carNumber LIKE '${carNumber}' AND personName LIKE '${personName}' AND cardStatus LIKE ${cardStatus}`
    } else if (carNumber && personName) {
      query += `carNumber LIKE '${carNumber}' AND personName LIKE '${personName}'`
    } else if (carNumber && (cardStatus === '0' || cardStatus)) {
      query += `carNumber LIKE '${carNumber}' AND cardStatus LIKE ${cardStatus}`
    } else if (personName && (cardStatus === '0' || cardStatus)) {
      query += `personName LIKE '${personName}' AND cardStatus LIKE ${cardStatus}`
    } else if (carNumber) query += `carNumber LIKE '${carNumber}'`
    else if (personName) query += `personName LIKE '${personName}'`
    else if ((cardStatus === '0' || cardStatus)) query += `cardStatus LIKE ${cardStatus}`
    console.log('查询参数:', query)
    connection.query(query, (err, results) => {
      if (err || results.length === 0) {
        return res.status(405).json({ code: 405, msg: '查询出错，请检查数据-01' })
      }
      const arr = results.map(row => ({
        id: row.id,
        personName: row.personName,
        phoneNumber: row.phoneNumber,
        carNumber: row.carNumber,
        carBrand: row.carBrand,
        cardStatus: row.cardStatus,
        totalEffectiveDate: row.totalEffectiveDate
      }))
      let newArr = []
      if (page === 1 && pageSize < arr.length) {
        for (let i = 0; i < pageSize; i++) {
          newArr.push(arr[i])
        }
      } else if ((page * pageSize) <= arr.length) {
        const start = (page - 1) * pageSize
        const end = page * pageSize
        for (let i = start; i < end; i++) {
          newArr.push(arr[i])
        }
      } else if ((page * pageSize) > arr.length) {
        const start = (page - 1) * pageSize
        const end = (arr.length % pageSize)
        for (let i = start; i < end; i++) {
          newArr.push(arr[i])
        }
      } else {
        newArr = arr
      }
      console.log('old', arr)
      console.log('new', newArr)
      res.status(200).send({
        code: 1000,
        msg: '获取信息成功',
        data: {
          total: arr.length,
          rows: newArr
        }
      })
    })
  } else {
    // 如果没有查询参数就可以使用分页功能
    connection.query('SELECT COUNT(*) as total FROM monthly_card', (err, countResult) => {
      if (err) {
        return res.status(500).json({ code: 500, msg: '服务器错误' })
      }
      //        数据库的总条数
      const count = countResult[0].total
      let startPage = page
      let endPage = pageSize
      if (page === 1 && pageSize < count) {
        startPage = 0
      } else if ((page * pageSize) <= count) {
        startPage = (page - 1) * pageSize
      } else if ((page * pageSize) > count) {
        startPage = (page - 1) * pageSize
        endPage = (count % pageSize)
      } else if (pageSize > count) {
        startPage = 0
        endPage = count
      }
      // 分页数据判断
      const pageQuery = `SELECT * FROM monthly_card ORDER BY id  LIMIT ${startPage},${endPage}`
      connection.query(pageQuery, (err, results) => {
        if (err || results.length === 0) {
          return res.status(405).json({ code: 405, msg: '请求错误-02' })
        }
        //            console.log(results)
        res.status(200).send({
          code: 1000,
          msg: '获取信息成功',
          data: {
            total: count,
            rows: results.map(row => ({
              id: row.id,
              personName: row.personName,
              phoneNumber: row.phoneNumber,
              carNumber: row.carNumber,
              carBrand: row.carBrand,
              cardStatus: row.cardStatus,
              totalEffectiveDate: row.totalEffectiveDate
            }))
          }
        })
      })
    })
  }
})
// INSERT INTO `demo_server`.`monthly_card` (`id`, `personName`, `phoneNumber`, `carNumber`, `carBrand`, `cardStatus`, `totalEffectiveDate`, `cardStartDate`, `cardEndDate`, `paymentAmount`, `paymentMethod`) VALUES ('31', '托尼', '13300000111', '粤A00000', 'BYD', '1', '365', '2024-10-08', '2025-01-29', '1', 'alipay');
app.post('/parking/card', (req, resa) => {
  const { personName, phoneNumber, carNumber, carBrand, cardStartDate, cardEndDate, paymentMethod, paymentAmount } = req.body
  const query = 'SELECT *FROM monthly_card WHERE carNumber LIKE ?'
  connection.query(query, [carNumber], (err, res) => {
    if (err || res.length > 0) {
      return resa.status(409).send({ msg: '当前车牌号已办理月卡', code: 409 })
    }
    const totalEffectiveDate = cardDate(cardStartDate, cardEndDate)
    let cardStatus = 1
    if (totalEffectiveDate > 1) cardStatus = 0
    else cardStatus = 1
    const insert = `INSERT INTO monthly_card (personName, phoneNumber, carNumber, carBrand,cardStatus, totalEffectiveDate,cardStartDate, cardEndDate, paymentMethod, paymentAmount) VALUES ?`
    const values = []
    values.push([personName, phoneNumber, carNumber, carBrand, cardStatus, totalEffectiveDate, cardStartDate, cardEndDate, paymentMethod, paymentAmount])
    console.log(insert + values)
    connection.query(insert, [values], (err, results) => {
      if (err) {
        return resa.status(509).send({ msg: `服务器错误+${err}` })
      }
      resa.status(200).send({ msg: '操作成功', code: 200 })
    })
  })
})

app.listen(8010, () => {
  console.log('Server is running on port 8010')
})
